package com.qf.ability.gateway.utils;

import com.alibaba.fastjson.JSON;
import com.qf.commons.base.result.Codes;
import com.qf.commons.base.result.R;
import com.qf.commons.base.result.Rs;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;

/**
 * author Ken
 * create_time 2022/11/28
 */
public class ResponseUtils {

    /**
     * 设置响应体的内容
     * @return
     */
    public static Mono result(ServerWebExchange exchange, Codes codes, Object data, HttpStatus httpStatus){
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置响应码
        response.setStatusCode(httpStatus);
        //设置响应头，指定响应体的数据类型
        response.getHeaders().add("Content-Type", "application/json;charset=utf-8");

        //设置响应内容
        DataBuffer dataBuffer = null;
        try {
            //需要返回的r对象
            R result = null;
            if (httpStatus == HttpStatus.OK) {
                result = Rs.create(data);
            } else {
                result = Rs.createFail(codes, data);
            }
            dataBuffer = response.bufferFactory().wrap(JSON.toJSONString(result).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return response.writeWith(Mono.just(dataBuffer));
    }
}
